var vcFunction = vcFunction || {
    fnGetDomain: function (url) {
        return (url.match(/:\/\/(.[^/]+)/)[1]).replace('www.', '');
    },
    fnCheckEmailValid: function (email) {
        var checkTLD = 1;
        var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
        var emailPat = /^(.+)@(.+)$/;
        var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
        var validChars = "\[^\\s" + specialChars + "\]";
        var quotedUser = "(\"[^\"]*\")";
        var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
        var atom = validChars + '+';
        var word = "(" + atom + "|" + quotedUser + ")";
        var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
        var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
        var matchArray = email.match(emailPat);

        if (matchArray == null) { //check if it conforms to typical patterns
            return false;
        }
        var user = matchArray[1];
        var domain = matchArray[2];
        for (i = 0; i < user.length; i++) {
            if (user.charCodeAt(i) > 127) {   //invalid chars in emailname
                return false;
            }
        }
        for (i = 0; i < domain.length; i++) {
            if (domain.charCodeAt(i) > 127) { //invalid chars in domain name
                return false;
            }
        }

        var atomPat = new RegExp("^" + atom + "$");
        var domArr = domain.split(".");
        var len = domArr.length;
        for (i = 0; i < len; i++) {
            if (domArr[i].search(atomPat) == -1) {
                return false;
            }
        }
        if (checkTLD && domArr[domArr.length - 1].length != 2 &&
            domArr[domArr.length - 1].search(knownDomsPat) == -1) {
            return false;
        }

        if (len < 2) {        //missing a hostname
            return false;
        }

        return true;
    },
    fnFullScreen: function () {
        element = document.body;
        // Supports most browsers and their versions.
        var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
        if (requestMethod) { // Native full screen.
            requestMethod.call(element);
        } else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    },
    getXOffset: function () {
        var pageX;
        if (typeof(window.pageXOffset) == 'number') {
            pageX = window.pageXOffset;
        }
        else {
            pageX = document.documentElement.scrollLeft;
        }
        return pageX;
    },
    getYOffset: function () {
        var pageY;
        if (typeof(window.pageYOffset) == 'number') {
            pageY = window.pageYOffset;
        }
        else {
            pageY = document.documentElement.scrollTop;
        }
        return pageY;
    },
    getOffset: function () {
        var offset = {};
        if (typeof(window.pageYOffset) == 'number') {
            offset.pageX = window.pageXOffset;
            offset.pageY = window.pageYOffset;
        }
        else {
            offset.pageX = document.documentElement.scrollLeft;
            offset.pageY = document.documentElement.scrollTop;
        }
        return offset;
    }
}
var vcCommon = vcCommon || {
    orgTitle: document.title,
    AJAX_TIMEOUT: 10000,


    ajaxPreloader: function (a, option) {
        _opt = {
            top: '48%',
            left: '50%'
        }
        $.extend(_opt, option);
        if (a == 'show')
            $('.ajax_loading').removeClass('hidden').css({top: _opt.top, left: _opt.left});
        else if (a == 'hide')
            $('.ajax_loading').addClass('hidden');
    },
    //Các hàm check dữ liệu - so sánh định dạng dữ liệu
    checkData: function (a, b) {
        for (var key in a) {
            if (!b.hasOwnProperty(key)) {
                return false;
            }
        }
        for (var key in b) {
            if (!a.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    },
    checkDataChild: function (parent, child) {
        for (var key in child) {
            if (!parent.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    },

    loadAjax: function (method, data, type, success, beforeSend, failure) {
        var failed = false;
        /**
         * timerError = setTimeout(function(){
 * 			alert('Có l?i x?y ra. Vui lòng th? l?i sau.', 'Thông báo');
 * 			failure();
 * 		}, vcCommon.AJAX_TIMEOUT);
         */
        timerError = 0;
        $.ajax({
            type: 'post',
            url: '/ajax/' + method,
            data: data,
            dataType: type,
            success: function (resp) {
                if (type == 'json') {
                    if (resp.err == -10 && resp.data) {
                        vcVar.ajaxToken = resp.data;
                        clearTimeout(timerError);
                        return vcCommon.loadAjax(method, data, type, success, beforeSend, failure);
                    }
                    if (failed)
                        return;
                    clearTimeout(timerError);
                    if (success)
                        success(resp);
                }
                else {
                    clearTimeout(timerError);
                    if (success)
                        success(resp);
                }
            },
            beforeSend: function () {
                if (beforeSend)
                    beforeSend();
            }
        });
    },//End loadAjax
    loadPjax: function () {
        try {
            $('a[data-pjax]').pjax({
                scrollTo: 0
            });
        } catch (err) {

        }
    }
};
$(function(){
    //form add to cart
    $(document).on('submit','#a2c-form',function(e){
        var form = $(this);
        e.preventDefault();
        $.ajax({
            type : form.attr('method'),
            data : form.serialize(),
            url  : form.attr('ajax-action'),
            dataType : 'json',
            success : function(resp){
                if(resp.code == 1){
                    window.location.href = resp.url;
                }
            }
        })
    });
    $('span','.btn_add_cart').click(function(){
        $('#a2c-form').submit();
    });
    //cập nhật giỏ hàng
    $('.sync-cart').click(function(e){
        e.preventDefault();
        var id = $(this).attr('data-element-id');
        $.ajax({
            type : 'post',
            url : '/ajax/changeCart',
            data : {id : id, number : $('#item_'+id).val(), action : 'sync'},
            dataType : 'json',
            success : function(resp){
                if(resp.code == 1){
                    $('#subtotal_'+id).html(resp.subtotal);
                    $('.cart-product-price-total').html(resp.total);
                }
            }
        })
    });
    $('.del-element').click(function(e){
        e.preventDefault();
        var id = $(this).attr('data-element-id');
        $.ajax({
            type : 'post',
            url : '/ajax/changeCart',
            data : {id : id, number : $('#item_'+id).val(), action : 'delete'},
            dataType : 'json',
            success : function(resp){
                if(resp.code == 1){
                    $('tr#row_'+id).hide();
                    $('.cart-product-price-total').html(resp.total);
                }
            }
        })
    })
});